package com.hsgene.consumables.controller;

import com.hsgene.common.ClientType;
import com.hsgene.common.util.jwt.IJWTInfo;
import com.hsgene.common.util.resolver.FromSession;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.support.LimitHelper;
import com.hsgene.common.util.web.session.UserInfo;
import com.hsgene.consumables.condition.ApplyCondition;
import com.hsgene.consumables.domain.ConsumablesApplyAudit;
import com.hsgene.consumables.domain.ConsumablesSendSignInfo;
import com.hsgene.consumables.dto.*;
import com.hsgene.consumables.dto.v1.operation.GoodsApplyModifyDto;
import com.hsgene.consumables.exception.ConsumablesErrorCode;
import com.hsgene.consumables.service.ConsumablesApplyService;
import com.hsgene.consumables.service.GoodsApplyService;
import com.hsgene.consumables.utils.JwtToken;
import com.hsgene.logistics.domain.LogisticsInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 耗材申请、发送、寄送
 *
 * @author wxf
 * @date 2018/8/15 8:44
 **/
@RestController
@RequestMapping("/v1.0/genetic/testing/goods/applys")
public class ConsumablesApplyController {

    /**
     * Log
     */
    private static final Logger LOGGER = LogManager.getLogger(ConsumablesApplyController.class);

    @Autowired
    private ConsumablesApplyService applyService;
    @Resource
    private GoodsApplyService goodsApplyService;
    @Resource
    private JwtToken jwtToken;

    /**
     * 耗材申请
     *
     * @param applyInfos
     * @return
     */
    @PostMapping("apply")
    public ApiResult<Map<String, String>> addConsumablesApplyInfo(@RequestBody ConsumablesApplyInfoDto applyInfos) {
        try {
            applyInfos.setCreateTime(new Date());
            if (applyInfos == null) {
                return ApiResult.fail(ConsumablesErrorCode.APPLY_IS_ERROR);
            }
            String result = applyService.addConsumablesApplyInfo(applyInfos);
            Map<String, String> map = new HashMap<>();
            map.put("applyNo", result);
            return new ApiResult<>(200, "success", "申请成功", map);
        } catch (Exception e) {
            LOGGER.error("add consumabels info is error", e);
            return ApiResult.fail(ConsumablesErrorCode.ADD_IS_ERROR);
        }
    }

    /**
     * 查看申请详情信息
     *
     * @param applyNo 申请编号
     * @return
     */
    @GetMapping("apply_details")
    public ApiResult<Object> getConsumablesApplyDetailsInfo(String applyNo) {
        try {
            Object applyInfo = applyService.getConsumablesApplyDetailsInfo(applyNo);
            return new ApiResult<>(200, "success", "查询详情成功", applyInfo);
        } catch (Exception e) {
            LOGGER.error("query consumabels details info is error", e);
            return ApiResult.fail(ConsumablesErrorCode.QUERY_IS_ERROR);
        }
    }

    /**
     * 发放耗材更新
     *
     * @param shipInfo 申请编号
     * @return
     */
    @PutMapping("ship")
    public ApiResult<String> updateConsumablesApplyInfo(@RequestBody ConsumablesApplyShipInfo shipInfo) {
        try {
            if (StringUtils.isEmpty(shipInfo.getApplyNo())) {
                return ApiResult.fail(ConsumablesErrorCode.UPDATE_IS_ERROR);
            }
            boolean result = applyService.updateConsumablesApplyInfo(shipInfo);
            return new ApiResult<>(200, "success", "发放成功", String.valueOf(result));
        } catch (Exception e) {
            LOGGER.error("update consumabels info is error", e);
            return ApiResult.fail(ConsumablesErrorCode.UPDATE_IS_ERROR);
        }
    }

    /**
     * 寄送耗材更新
     *
     * @param expressInfoDto
     * @return
     */
    @PutMapping("send")
    public ApiResult<String> sendConsumablesApplyInfo(@RequestBody ConsumablesExpressInfoDto expressInfoDto) {
        try {
            Date date = new Date();
            expressInfoDto.setUpdateDate(date);
            //寄送时间
            expressInfoDto.setSendDate(date);
            boolean result = applyService.sendConsumablesApply(expressInfoDto);
            return new ApiResult<>(200, "success", "寄送更新成功", String.valueOf(result));
        } catch (Exception e) {
            LOGGER.error("update consumabels info is error", e);
            return ApiResult.fail(ConsumablesErrorCode.UPDATE_IS_ERROR);
        }
    }

    /**
     * 确认签收完成
     *
     * @param applyNo 申请单号
     * @return
     */
    @PutMapping("receipt")
    public ApiResult<String> receiptConsumablesInfo(String applyNo) {
        try {
            boolean result = applyService.receiptConsumablesInfo(applyNo, new Date());
            return new ApiResult<>(200, "success", "签收更新成功", String.valueOf(result));
        } catch (Exception e) {
            LOGGER.error("update consumabels info is error", e);
            return ApiResult.fail(ConsumablesErrorCode.UPDATE_IS_ERROR);
        }
    }

    /**
     * 查看寄送物流信息
     *
     * @param applyNo 申请单号
     * @return
     */
    @GetMapping("consumbles_express")
    public ApiResult<List<LogisticsInfo>> queryExpressInfo(String applyNo) {
        try {
            return applyService.queryExpressInfo(applyNo);
        } catch (Exception e) {
            LOGGER.error("query consumbles express is error...", e);
            return ApiResult.fail(ConsumablesErrorCode.QUERY_IS_ERROR);
        }
    }

    /**
     * 获取列表信息
     *
     * @param condition 条件信息
     * @return
     */
    @PostMapping("query_list")
    public ApiResult<List<ConsumablesListInfoDto>> queryConsumblesList(@RequestBody ConsumablesQueryCondition
                                                                               condition) {
        try {
            List<ConsumablesListInfoDto> result = applyService.queryConsumblesList(condition);
            return new ApiResult<>(200, "success", "查询成功", result);
        } catch (Exception e) {
            LOGGER.error("query list is error...", e);
            return ApiResult.fail(ConsumablesErrorCode.QUERY_IS_ERROR);
        }
    }

    /**
     * 耗材审核列表
     * @param applyCondition
     * @return
     */
    @PostMapping("page")
    public ApiResult queryApplys(@RequestBody ApplyCondition applyCondition){
        try {

            ApiResult apiResult = applyService.queryApplys(applyCondition);
            return apiResult;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("query apply page error...", e);
            return ApiResult.fail(ConsumablesErrorCode.GENETIC_GOODS_APPLY_PAGE_ERROR);
        }
    }

    /**
     * 耗材审核寄送弹窗展示信息获取
     * @param id
     * @return
     */
    @GetMapping("baseInfo/{id}")
    public ApiResult applyBaseInfo(@PathVariable("id") String id){
        try {
            ApiResult apiResult = applyService.applyBaseInfo(id);
            return apiResult;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("query apply baseInfo error...", e);
            return ApiResult.fail(ConsumablesErrorCode.APPLY_BASE_INFO_ERROR);
        }
    }

    /**
     * 耗材寄送信息录入
     * @param consumablesSendSignInfoDto
     * @return
     */
    @PutMapping("send/info")
    public ApiResult applySendSign(@RequestBody ConsumablesSendSignInfo consumablesSendSignInfoDto){
        try {
            return applyService.applySendSign(consumablesSendSignInfoDto);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("genetic goods send sign error...", e);
            return ApiResult.fail(ConsumablesErrorCode.UPDATE_IS_ERROR);
        }
    }

    /**
     * 耗材申请详情
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public ApiResult applyDetail(@PathVariable("id")String id,Integer platform){
        try {
            //根据平台参数判断是花生仁还是运营后台
            if(ClientType.CONSOLE.getCode().equals(platform)){
                ApiResult apiResult = applyService.queryApplyDetail(id);
                return apiResult;
            }else if(ClientType.PEANUT.getCode().equals(platform)){
                //花生仁
                return applyService.peanutApplyDetail(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("genetic goods apply detail error...", e);
            return ApiResult.fail(ConsumablesErrorCode.GENETIC_GOODS_APPLY_DETAIL_ERROR);
        }
        return new ApiResult(5001,"failed","客户端类型不能为空",null);
    }

    /**
     * 耗材申领详情列表
     * @param id 耗材申领编号
     * @param page 页码
     * @param size 大小
     * @return
     */
    @GetMapping("{id}/list")
    public ApiResult applyDetailPage(@PathVariable("id")String id,Integer page,Integer size){
        try {
            LimitHelper limitHelper = LimitHelper.create(page, size);
            ApiResult apiResult = applyService.queryApplyDetailPage(id, limitHelper);
            return apiResult;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("genetic goods apply detail page error...", e);
            return ApiResult.fail(ConsumablesErrorCode.GENETIC_GOODS_APPLY_DETAIL_ERROR);
        }
    }

    /**
     * 审核耗材申请
     * @param consumablesApplyAudit
     * @return
     */
    @PutMapping("/audit")
    public ApiResult auditStatus(@RequestBody ConsumablesApplyAudit consumablesApplyAudit, @FromSession UserInfo userInfo){
        try {
            if(userInfo!=null){
                consumablesApplyAudit.setAuditorId(userInfo.getUserId());
            }else {
                return new ApiResult(5001,"failed","用户信息错误，请重新登录",null);
            }
            return applyService.auditStatus(consumablesApplyAudit);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("audit apply error ...", e);
            return ApiResult.fail(ConsumablesErrorCode.AUDIT_APPLY_ERROR);
        }
    }

    /**
     * 根据地服ID和关键字搜索已有耗材列表
     * @param keyWords 关键字
     * @return
     */
    @GetMapping("keyWords")
    public ApiResult groundServantGoods(String keyWords,HttpServletRequest request){
        String groundServantId;
        try {
            String authorization = request.getHeader("Authorization");
            if (StringUtils.isBlank(authorization)) {
                authorization = request.getHeader("authorization");
            }
            IJWTInfo jwtInfo = jwtToken.getInfoFromToken(authorization);
            groundServantId = jwtInfo.getId();
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("ground servant goods error ...", e);
            return new ApiResult(500,"failed","获取信息出错",null);
        }
        return applyService.groundServantGoods(groundServantId,keyWords);
    }

    /**
     * 耗材申领列表
     * @param size 分页大小
     * @param page 页码
     * @param listType 前端分类（申领状态）
     * @param sort 排序条件（0-按下单时间倒排序1-按更新时间倒排序）
     * @return
     */
    @GetMapping("")
    public ApiResult peanutApplys(@RequestParam(defaultValue = "1")Integer page,
                                   @RequestParam(defaultValue = "10")Integer size,
                                   Integer listType,Integer sort,Integer platform,
                                  ApplyCondition applyCondition){
        try {
            LimitHelper limitHelper = LimitHelper.create(page, size, true);
            if(ClientType.PEANUT.getCode().equals(platform)){
                return applyService.peanutApplys(limitHelper,listType,sort);
            }else if (ClientType.CONSOLE.getCode().equals(platform)){
                applyCondition.setLimitHelper(limitHelper);
                return applyService.queryApplys(applyCondition);
            }else {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(500,"failed","获取数据失败",e.toString());
        }
    }

    /**
     * 花生仁耗材申领签收和修改耗材申请
     * @param id
     * @param goodsApplyModifyDto 操作码 difu_recieved为签收，difu_canceled为取消
     * @return
     */
    @PutMapping("/{id}")
    public ApiResult peanutSignIn(@PathVariable("id")String id,@RequestBody GoodsApplyModifyDto goodsApplyModifyDto){
        try {
            if(StringUtils.isNotEmpty(goodsApplyModifyDto.getType())){
                if("difu_recieved".equals(goodsApplyModifyDto.getType())){
                    return applyService.peanutSignIn(id);
                }else {
                    return applyService.peanutDelete(id);
                }
            }else {
                goodsApplyModifyDto.setApply_id(id);
                return goodsApplyService.updateGoodsApply(goodsApplyModifyDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(500,"failed","操作失败",e.toString());
        }
    }
}
